<template>
  <div
    style="
      display: flex;
      justify-content: space-between;
      gap: 10px;
      width: 100%;
      align-items: center;
    "
  >
    项目路径
    <el-radio-group v-model="codeLocation">
      <el-radio v-for="item in codeLocations" :key="item.value" :value="item.value" size="middle">{{
        item.label
      }}</el-radio>
    </el-radio-group>
    <el-input
      v-model="repoPath"
      style="flex: 1"
      ref="pathInput"
      placeholder="请输入项目路径"
    ></el-input>
    <el-input
      v-if="codeLocation === 'my'"
      v-model="token"
      style="flex: 1"
      placeholder="请输入token"
    ></el-input>
    <el-button type="primary" @click="submit">提交</el-button>
  </div>
  <table-easy
    v-if="allList.length"
    ref="tableEasy"
    :list="list.list"
    :columns="columns"
    :filterArr="filterArr"
    :tableType="tableType"
    :showIndex="true"
    :showSelect="true"
    @changeSelect="changeSelect"
    :default-sort="{ prop: 'date', order: 'descending' }"
    :showPagination="true"
    :showBatchAction="false"
    @updateList="updateList"
    row-key="hash"
    :total="total.length"
  >
    <!-- 表头插槽 -->
    <template #index>序号</template>
    <!-- 表格插槽 -->
    <template #date="{ row }">
      {{ formatTime(row.date, 'YYYY-MM-DD HH:mm:ss') }}
    </template>
    <template #hash="{ row }">
      <span v-copy="row.hash" class="iconfont icon-fuzhi"></span>{{ row.hash }}
    </template>
    <template #message="{ row }">
      <span v-copy="row.message" class="iconfont icon-fuzhi"></span>{{ row.message }}
    </template>
    <!-- 筛选器插槽 -->
    <template #fields="{ selectedCondition, filterConditions }">
      <div v-for="domain in selectedCondition" :key="domain.key">
        <el-form-item :label="domain.label" :prop="domain.key">
          <el-select
            v-if="domain.key === 'author'"
            v-model="filterConditions.author"
            clearable
            placeholder="输入姓名"
          >
            <el-option
              v-for="item in authorList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-input
            v-if="domain.key === 'message'"
            v-model="filterConditions.message"
            clearable
            placeholder="输入关键字"
          />
          <el-date-picker
            v-if="domain.key === 'date'"
            v-model="filterConditions.date"
            type="daterange"
            range-separator="-"
            start-placeholder="开始"
            end-placeholder="结束"
          />
        </el-form-item>
      </div>
    </template>
    <!-- 顶部自定义按钮区域 -->
    <template #outerAction>
      <el-button type="primary" size="small" @click="exportGit">导出</el-button>
      <el-button type="primary" size="small" @click="editText">文本</el-button>
    </template>
  </table-easy>
  <TextView v-model:dialog="dialogShow" v-model:text="dialogText" />
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import TableEasy from '@/components/TableEasy.vue'
import { mathService } from '@/service/index'
import search, { exportExcel, formatData } from '@/tools/frontSearch'
import { getGiteeCommits } from '@/tools/gitEE'
import TextView from './TextView.vue'
import type { List } from '@/types/global.d'
interface ListWraper {
  list: List[]
}
const tableType = 'git'
const list = reactive<ListWraper>({ list: [] })
const columns = [
  {
    key: 'hash',
    label: '哈希',
    width: 400,
    search: false,
    sortable: false
  },
  {
    key: 'date',
    label: '日期',
    width: 160,
    search: true,
    sortable: true,
    isArray: true
  },
  {
    key: 'author',
    label: '提交人',
    width: 100,
    search: true,
    sortable: false
  },
  {
    key: 'message',
    label: '记录',
    width: 350,
    search: true,
    sortable: false
  }
]
const allList = ref<List[]>([])
const authorList = ref<string[]>([])

const codeLocations = reactive([
  { label: '本地', value: 'local' },
  { label: '码云', value: 'my' }
])
const codeLocation = ref<string>('local')

const repoPath = ref<string>('D:/中电自能/al_ele_screen_front')
const token = ref<string>('')
onMounted(() => {
  submit()
})

async function submit() {
  if (!repoPath.value) {
    pathInput.value?.focus()
    return ElMessage.info('请输入路径')
  }
  let res = []
  if (codeLocation.value === 'local') {
    res = await localGit()
  } else {
    res = await gitEE()
  }
  allList.value = res
  authorList.value = [...new Set(allList.value.map((item) => item.author))]
  tableEasy.value?.handleSearch()
}

// 获取提交记录
const pathInput = ref<HTMLInputElement | null>(null)
const tableEasy = ref<InstanceType<typeof TableEasy> | null>(null)
async function localGit() {
  const res: { code: number; data: List[] } = await mathService.post('/workLog/git', {
    repoPath: repoPath.value
  })
  if (res.code === 0) {
    allList.value = []
    authorList.value = []
    ElMessage.error('未查询到提交信息')
    return []
  }
  return res.data
}
// 获取码云仓库
async function gitEE() {
  try {
    const res = await getGiteeCommits(repoPath.value)
    return res.map((item) => ({
      hash: item.sha,
      author: item.commit.author.name,
      message: item.commit.message,
      date: dayjs(item.commit.committer.date).valueOf()
    }))
  } catch (error: any) {
    ElMessage.error(error.message)
    return []
  }
}
// 默认筛选器
const filterArr = [
  {
    filterAttrs: [
      { key: 'author', show: true, value: [] },
      { key: 'date', show: true, value: [] },
      { key: 'message', show: true, value: [] }
    ],
    filterName: '查询条件',
    filterType: tableType,
    id: 101,
    isCurrent: true,
    isSystem: 1,
    selected: 1
  }
]
// 改变选择
const selectIds = ref<string[]>([])
const changeSelect = (data: List[]) => {
  selectIds.value = data.map((item) => item.hash)
}
const total = ref<List[]>([])
import dayjs from 'dayjs'
const updateList = (val: any) => {
  if (val?.date?.length) {
    val.date[0] = dayjs(val.date[0]).valueOf()
    val.date[1] = dayjs(val.date[1]).valueOf() + 86400000 - 1
  }
  const res = search<List>(allList.value, val, ['message'])
  list.list = res[0]
  total.value = res[1]
}
// 日期格式化
import { formatTime } from '@/tools/index'
import { ElMessage } from 'element-plus'
// git记录导出
const exportGit = () => {
  let list = total.value
  if (selectIds.value.length) {
    list = list.filter((item) => selectIds.value.includes(item.hash))
  }
  exportExcel(list)
}

// 提交记录文本编辑
const dialogShow = ref(false)
const dialogText = ref('')
function editText() {
  const arr = formatData(total.value)
  dialogText.value = arr
    .map((item: { 日期: string; 内容: string }) => [item.日期, item.内容])
    .flat()
    .join('\n')
  dialogShow.value = true
}
</script>
<style lang="less" scoped>
.icon-fuzhi {
  cursor: pointer;
}
</style>
